package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.Answer;
import cn.wolfcode.luowowo.comment.query.AnswerQuery;
import cn.wolfcode.luowowo.comment.repository.IAnswerRepository;
import cn.wolfcode.luowowo.comment.service.IAnswerService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@SuppressWarnings("all")
@Service
public class AnswerServiceImpl implements IAnswerService {

    @Autowired
    private IAnswerRepository repository;//分页,排序,crud

    @Autowired
    private MongoTemplate template;//高级查询


    @Override
    public void saveOrUpdate(Answer answer) {
        if(!StringUtils.hasLength(answer.getId())){
            //设置创建时间
            answer.setCreateTime(new Date());
        }
        repository.save(answer);
    }

    @Override
    public void save(Answer answer) {
        if (answer != null){
            answer.setCreateTime(new Date());
        }
        repository.save(answer);
    }

    @Override
    public Page query(AnswerQuery qo) {
        //mongodb查询对象
        Query query = new Query();

        //查询条件
        if (qo.getQuestionId() != null){
            Criteria criteria = Criteria.where("questionId").is(qo.getQuestionId());
            query.addCriteria(criteria);
        }
        //查总数
        Long count = template.count(query, Answer.class);
        //若总条数为空,无需再往下执行
        if (count == null){
            return Page.empty();
        }
        //分页对象
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "thumbupnum");
        query.with(pageable);

        //查询当前页的数据
        List<Answer> list = template.find(query, Answer.class);

        return new PageImpl<>(list,pageable,count);
    }


    @Override
    public void answerThumbUp(String aid, Long uid) {
        //获取当前的回答
        Optional<Answer> optional = repository.findById(aid);
        Answer answer = optional.get();

        if (answer == null){
            return;
        }
        //点赞用户id集合
        List<Long> thumbuplist = answer.getThumbuplist();
        //判断是点赞还是取消点赞
        if (thumbuplist.contains(uid)){
            //表示取消点赞
            answer.setThumbupnum(answer.getThumbupnum() - 1);
            thumbuplist.remove(uid);
        }else{
            //表示点赞
            answer.setThumbupnum(answer.getThumbupnum() + 1);
            thumbuplist.add(uid);
        }
        repository.save(answer);
    }
}
